<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Category extends MY_Controller {

	/**
	 * 商品分类
	 * @var ConsumerCategoryModel
	 */
	public $mCategory;
	
	/**
	 * 商家
	 * @var MerchantUserModel
	 */
	public $mMerchant;
	
	public function __construct(){
		parent::__construct();		
		$this->loadModel('ConsumerCategoryModel', 'mCategory', 'consumer');
		$this->loadModel('MerchantUserModel', 'mMerchant', 'merchant');
	}
	
	/**
	 * 首页
	 */
	public function index(){

		$data = array(
				'title'=>'商品分类',
				'level'=>0,//一级分类
		);
		
		$this->view('product/category/home', $data, 'datatable,select2,cropit_master,validation,uniform,datepicker');
	}
	
	/**
	 * 二级分类页面
	 */
	public function details(){
		$parentId = get('pid');
		if ( ! $parentId){
			show_404();
		}
		
		//如果该分类不存在也404
		$tCategory = $this->mCategory->getInfo($parentId);
		
		$data = array(
				'title'=>'“'.$tCategory['cat_name'].'”二级分类列表',
				'category'=>$tCategory,
				'level'=>1,
		);
		
		$this->view('product/category/details', $data, 'datatable,select2,cropit_master,validation,uniform,datepicker');
	}
	
	/**
	 * 保存|修改
	 */
	public function save(){
		//表单验证
		$vConf = array(
				array('cat_name', '分类名称', 'required'),
				array('status', '状态', 'required|is_natural_no_zero'),
				array('sort', '排序', 'required|is_natural_no_zero'),
// 				array('parent_id', '上级id', 'required'),
				array('type', '商家分类', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);
		
		$id = post('id');
		$cat_name = post('cat_name');
		$status = post('status');
		$sort = post('sort');
		$parentId = post('parent_id');
		$type = post('type');
		$portrait = post('portrait');
		
		if (! $id && ! post('portrait')){
			$this->ajaxReturn(0,'图标未上传');
		}
		
		$data = array(
				'parent_id'=>$parentId ? : 0,
				'type'=>$type,
				'cat_name'=>$cat_name,
				'status'=>$status,
				'sort'=>$sort,
		);
		$this->db->trans_begin();
		
		if ($id){
			$tId = $this->mCategory->save($data,$id);
			if(!$tId){
				$this->db->trans_rollback();
				$this->ajaxReturn(0,'保存失败');
			}
		}else {
			$data['addtime'] = time();
			$tId = $this->mCategory->save($data);
			if(!$tId){
				$this->ajaxReturn(0,'保存失败');
			}
		}
		
		$tId = $id?:$tId;
		
		/**
		 *  移动新文件
		 */
		if($portrait){
			$path = 'uploads/product/category/'.$tId.'/';
			$ts = saveCSVimg(array($portrait), $path,$tId,true);
			if($ts !== false){
				$tId = $this->mCategory->save(array('pic'=>$ts[0]), $tId);
				if( ! $tId){
					$this->appReturn(0, '保存失败');
				}
			}else{
				$this->ajaxReturn(0, '图标上传失败');
			}
		}
		
		$this->db->trans_commit();
		$this->ajaxReturn(1,'保存成功');
	}

	/**
	 * 获取信息
	 */
	public function getInfo(){
		$id = get('id');
		if (! $id){
			$this->ajaxReturn(0,'id不存在');
		}
		
		$info = $this->mCategory->getInfo($id);
		$info['pic'] = isset($info['pic']) ? getImage($info['pic'],'og') : '';
		echo json_encode($info);
	}
	
	/**
	 * 获取列表
	 */
	public function getList(){
		$custom = get('custom');//是否是商家分类[该参数，在页面中getlist传递标识]
		
		$data = $this->mCategory->adminGetList();
		
		//获取上级分类
		$c_ids = array();
		$tCategory = array();
		if ($data['data']){
			foreach ($data['data'] as $k=>$v){
				if ( ! in_array($v['parent_id'], $c_ids)){
					$c_ids[] = $v['parent_id'];
				}
			}
			
			if ($c_ids){
				$tCategory = $this->mCategory->getInfoByIds($c_ids);
			}
		}
		
		foreach ($data['data'] as $k=>$v){
			
			$info_url = getUrl('product/category/details?pid='.$v['id']);
			if ($custom){
				$info_url = getUrl('product/category/custom?pid='.$v['id']);
			}
			
			$data['aaData'][$k][] = '<img width="100%" src="'.getImage($v['pic'],'xs').'" class="img-wh"/>';
			$data['aaData'][$k][] = '<a href="'.$info_url.'">'.$v['cat_name'].'</a>';
			$data['aaData'][$k][] = isset($tCategory[$v['parent_id']]) ? $tCategory[$v['parent_id']]['cat_name'] : '暂无';
			$data['aaData'][$k][] = date('Y-m-d H:i:s',$v['addtime']);
            $status = $v['status'] == 1 ? 2 : 1;
            $data['aaData'][$k][] = "<a href='".getUrl('product/category/changeStatus?id=').$v['id'].
                "' class='ajax-request-btn deco' alert-message='是否确认".$this->adminStatus($status)."'>".$this->adminStatus($v['status'],true)."</a>";
			$btnConfig = adminCreateBtn(
					array(
                        'label' => '编辑',
                        'attr' => array(
                            'href' => getUrl('product/category/getInfo?id='.$v['id']),
                            'class' => 'btn btn-xs blue-stripe default edit-btn'
                        ),
                        'tag' => 'a',
                        'permissions' => array(
                            'module' => 'product',
                            'key' => 'category-edit'
                        )

					));
			if($v['id']>3){
                $btnConfig .= ' '.adminCreateBtn(array(
                        'label' => '分类',
                        'attr' => array(
                            'href' => $info_url,
                            'class' => 'btn btn-xs green-stripe default'
                        ),
                        'tag' => 'a',
                        'permissions' => array(
                            'module' => 'product',
                            'key' => 'category-details'
                        )
                    ));
                $btnConfig .= ' '.adminCreateBtn(array(
                        'label' => '删除',
                        'attr' => array(
                            'href' => getUrl('product/category/deleteCategory?id='.$v['id']),
                            'class' => 'btn btn-xs red-stripe default ajax-request-btn',
                            'alert-message'=>'确定删除分类 “ '.$v['cat_name'].' ” ?',
                        ),
                        'tag' => 'a',
                        'permissions' => array(
                            'module' => 'product',
                            'key' => 'category-details'
                        )
                    ));
            }

			$data['aaData'][$k][] = $btnConfig;
		}

		unset($data['data']);
		echo json_encode($data);
	}

    /**
     * 删除商品分类
     * @author heyu
     */
    public function deleteCategory(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
        $id = (int)get('id');
        $info = $this->mCategory->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在或已删除');
        }

        //查看分类下是否有分类
        if ($info['parent_id'] == 0){
            $cat = $this->mCategory->getCategoryList($id, true);
            if (!empty($cat)){
                $this->ajaxReturn(0, '请先该分类下的分类');
            }
        }else{
            $cus = $this->mCategory->getCustomList(0, $id, $info['parent_id']);
            if ($cus){
                $this->ajaxReturn(0, '请先该分类下的分类');
            }
        }
        $tA = $this->mCategory->deleteCategory($id);
        if (!$tA){
            $this->ajaxReturn(0, '删除失败');
        }
        $this->ajaxReturn(1, '删除成功');
    }

    /**
     * 修改商品状态
     * @author heyu
     */
    public function changeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = get('id');
        $info = $this->mCategory->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在');
        }
        $status = $info['status'] == 1 ? 2 : 1;
        if($this->mCategory->save(array('status' => $status), $id)){
            $this->ajaxReturn(1, '已保存');
        }
        $this->ajaxReturn(0, '保存失败');
    }

	//////////////////////////////////////////////////////////////////
	//+---------------------------------------------------------
	//|	自定义分类
	//+-----------------------------------------------------

	/**
	 * 商家分类页面
	 */
	public function custom(){
		$parentId = get('pid');
		if ( ! $parentId){
			show_404();
		}

		//如果该分类不存在也404
		$tCategory = $this->mCategory->getInfo($parentId);
		if (! $tCategory){
			show_404();
		}
		$data = array(
				'title'=>'“'.$tCategory['cat_name'].'”自定义分类列表',
				'category'=>$tCategory,
				'level'=>1,
                'merchant' => $this->mCategory->getAllMerchantByCateId($parentId)
		);

		$this->view('product/category/custom', $data, 'datatable,select2,cropit_master,validation,uniform,datepicker');
	}

	/**
	 * 保存|修改 商家自定义分类
	 */
	public function saveCustom(){
		//表单验证
		$vConf = array(
				array('cat_name', '分类名称', 'required'),
				array('status', '状态', 'required|is_natural_no_zero'),
				array('merchant_id', '所属商家', 'required|is_natural_no_zero'),
				array('category_id', '上级分类', 'required|is_natural_no_zero'),
		);
		$this->formDataValidation($vConf);

		//获取参数
		$id 			= (int)post('id');
		$cat_name 		= trim(post('cat_name'));
		$status 		= (int)post('status');
		$category_id 	= (int)post('category_id');
		$merchant_id 	= (int)post('merchant_id');

		//验证分类是否存在
		$tCategory = $this->mCategory->getInfo($category_id);
		if (! $tCategory){
			$this->ajaxReturn(0,'上级分类不存在');
		}

		$tMerchant = $this->mMerchant->getInfo($merchant_id);
		if (! $tMerchant){
			$this->ajaxReturn(0,'该商家不存在');
		}

		//数据
		$data = array(
				'category_id'=>$category_id,
				'merchant_id'=>$merchant_id,
				'cat_name'=>$cat_name,
				'status'=>$status,
				'parent_id'=>$tCategory['parent_id'],
		);

		//开启事务
		$this->db->trans_begin();

		if ($id){
			//修改
			$tId = $this->mCategory->saveCustom($data,$id);
			if(!$tId){
				$this->db->trans_rollback();
				$this->ajaxReturn(0,'保存失败');
			}
		}else {
			//新增
			$data['addtime'] = time();
			$tId = $this->mCategory->saveCustom($data);
			if(!$tId){
				$this->ajaxReturn(0,'保存失败');
			}
		}

		$this->db->trans_commit();
		$this->ajaxReturn(1,'保存成功');
	}

	/**
	 * 获取信息
	 */
	public function getCustomInfo(){
		$id = get('id');
		if (! $id){
			$this->ajaxReturn(0,'id不存在');
		}

		$info = $this->mCategory->getCustomInfo($id);
		//获取商家名称
		$tMerchant = $this->mMerchant->getInfo($info['merchant_id']);
		$info['merchant_name'] = isset($tMerchant['shop_name']) ? $tMerchant['shop_name'] : '';
		//$info['pic'] = getImage($info['pic'],'og');
		echo json_encode($info);
	}

	/**
	 * 获取列表
	 */
	public function getCustomCategoryList(){

		$data = $this->mCategory->adminGetCustomCategoryList();

		//获取上级分类
		$c_ids = array();
		$m_ids = array();
		$tCategory = array();
		if ($data['data']){
			foreach ($data['data'] as $k=>$v){
				if ( ! in_array($v['category_id'], $c_ids)){
					$c_ids[] = $v['category_id'];
				}
				if ( ! in_array($v['merchant_id'], $m_ids)){
					$m_ids[] = $v['merchant_id'];
				}
			}

			if ($c_ids){
				$tCategory = $this->mCategory->getInfoByIds($c_ids);
			}
			if ($m_ids){
				$tMerchant = $this->mMerchant->getInfoByIds($m_ids);
			}
		}

		foreach ($data['data'] as $k=>$v){
			$data['aaData'][$k][] = $v['cat_name'];
			$data['aaData'][$k][] = isset($tCategory[$v['category_id']]) ? $tCategory[$v['category_id']]['cat_name'] : '暂无';
			$data['aaData'][$k][] = isset($tMerchant[$v['merchant_id']]) ? '<a href="'.getUrl('member/merchant/details?id='.$v['merchant_id']).'">'.$tMerchant[$v['merchant_id']]['shop_name'].'</a>' : '暂无';
			$data['aaData'][$k][] = date('Y-m-d H:i:s',$v['addtime']);
            $status = $v['status'] == 1 ? 2 : 1;
            $data['aaData'][$k][] = "<a href='".getUrl('product/category/changeCustomStatus?id=').$v['id'].
                "' class='ajax-request-btn deco' alert-message='是否确认".$this->adminStatus($status)."'>".$this->adminStatus($v['status'],true)."</a>";
			$btnConfig = adminCreateBtn(array(
							'label' => '编辑',
							'attr' => array(
									'href' => getUrl('product/category/getCustomInfo?id='.$v['id']),
									'class' => 'btn btn-xs blue-stripe default edit-btn'
							),
							'tag' => 'a',
							'permissions' => array(
									'module' => 'classes',
									'key' => 'edit'
							)
					));
            $btnConfig .= ' '.adminCreateBtn(array(
							'label' => '删除',
							'attr' => array(
									'href' => getUrl('product/category/deleteCustomCategory?id='.$v['id'].'&merchantId='.$v['merchant_id']),
									'class' => 'btn btn-xs red-stripe default ajax-request-btn',
                                    'alert-message'=>'确定删除分类 “ '.$v['cat_name'].' ” ?',
							),
							'tag' => 'a',
							'permissions' => array(
									'module' => 'classes',
									'key' => 'edit'
							)
					));
			$data['aaData'][$k][] = $btnConfig;
		}
		
		unset($data['data']);
		echo json_encode($data);
	}

    /**
     * 删除自定义分类
     * @author heyu
     */
    public function deleteCustomCategory(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
            array('merchantId', '商家di', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $this->loadModel('ConsumerProductModel', 'mProduct', 'consumer');
        $id = (int)get('id');
        $merchantId = (int)get('merchantId');
        $customInfo = $this->mCategory->getCustomInfo($id);
        if (!$customInfo){
            $this->ajaxReturn(0, '数据不存在或已删除');
        }
        //查看分类下是否有商品
        $total = $this->mProduct->getProductTotalByCategoryId($id);
        if ($total){
            $this->ajaxReturn(0, '请先删除分类下的产品');
        }
        $tA = $this->mCategory->deleteCustomCategory($id, $merchantId);
        if (!$tA){
            $this->ajaxReturn(0, '删除失败');
        }
        $this->ajaxReturn(1, '删除成功');
    }

    /**
     * 修改自定义商品状态
     * @author heyu
     */
    public function changeCustomStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = get('id');
        $info = $this->mCategory->getCustomInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在');
        }
        $status = $info['status'] == 1 ? 2 : 1;
        if($this->mCategory->saveCustom(array('status' => $status), $id)){
            $this->ajaxReturn(1, '已保存');
        }
        $this->ajaxReturn(0, '保存失败');
    }
}
